const mysql = require("mysql2");
const util = require("util");
const {getDataBaseOne} = require("./sqlite");

function underscoreToCamelCase(str) {
    return str.replace(/_([a-z])/g, function (match, letter) {
        return letter.toUpperCase();
    });
}


function matchTableNameAndFeids({searchString, databaseId}) {
    return new Promise(async (resolve) => {
        var tableNames = [];
        var fieldNames = [];
        var datasource = await getDataBaseOne({databaseId});
        const connection = mysql.createConnection({
            host: (datasource && datasource.host) || "127.0.0.1",
            port: (datasource && datasource.port) || 3306,
            user: (datasource && datasource.user) || "root",
            password: (datasource && datasource.password) || "",
            database: (datasource && datasource.database) || "szq_mes",
        });

        connection.connect();

        const query = util.promisify(connection.query).bind(connection);

        // 查询数据库中的所有表名
        var results = await query("SHOW TABLES");
        // console.  log('匹配的表名：');
        results.forEach((result) => {
            if (
                result[`Tables_in_${connection.config.database}`].match(
                    new RegExp(searchString, "i")
                )
            ) {
                // console.log(result[`Tables_in_${connection.config.database}`]);
                tableNames.push(result[`Tables_in_${connection.config.database}`]);
            }
        });

        // 查询每个表的字段和备注
        for (let i = 0; i < results.length; i++) {
            var result = results[i];
            const tableName = result[`Tables_in_${connection.config.database}`];

            var results2 = await query(`SHOW FULL COLUMNS FROM ${tableName}`);
            // console.log(`表 ${tableName} 的匹配的字段和备注：`);
            results2.forEach((result) => {
                if (
                    result.Field.match(new RegExp(searchString, "i")) ||
                    result.Comment.match(new RegExp(searchString, "i"))
                ) {
                    // console.log(`表 ${tableName} 的匹配的字段和备注： 字段名：${result.Field}，备注：${result.Comment}`);
                    fieldNames.push(
                        `表 ${tableName} 的匹配的字段和备注： 字段名：${result.Field}，备注：${result.Comment}`
                    );
                }
            });
        }

        connection.end();

        return resolve({
            tableNames,
            fieldNames,
        });
    });
}

const lodash = require('lodash')

async function showddl({tableName, databaseId}) {
    var datasource = await getDataBaseOne({databaseId});
    const connection = mysql.createConnection({
        host: (datasource && datasource.host) || "127.0.0.1",
        port: (datasource && datasource.port) || 3306,
        user: (datasource && datasource.user) || "root",
        password: (datasource && datasource.password) || "",
        database: (datasource && datasource.database) || "szq_mes",
    });
    connection.connect();

    const query = util.promisify(connection.query).bind(connection);

    const sql = `SHOW CREATE TABLE ${tableName}`;
    var strresult = await query(sql);

    // 关闭数据库连接
    connection.end();

    return strresult;
}

// 随机方法 1-100之间
function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 0;
            break;
    }
}

const {Parser} = require('sql-ddl-to-json-schema');
const parser = new Parser('mysql');

function parsejsonfromddl(ddl) {
    ddl = ddl + ";";
    const jsonSchemaDocuments = parser.feed(ddl).toJsonSchemaArray({});
    var one = jsonSchemaDocuments && jsonSchemaDocuments[0]
    var json = one && one.properties
    var newJson = {}
    lodash.map(json, (value, key) => {
        newJson[underscoreToCamelCase(key)] = ''
    })
    console.log(one);
    return {success: true, data: newJson}
}

module.exports = {
    parsejsonfromddl,
    matchTableNameAndFeids,
    showddl,
};
